// 日志方法
export const log = window.console;

/**
 * 序列化化数据
 * @param  {Object} data 数据对象
 * @return {String}      URL用数据
 */
export function serialize(data) {
  let str = '';
  Object.keys(data).forEach((key) => {
    str += `${key}=${encodeURIComponent(data[key])}&`;
  });
  str = str.replace(/&$/, '');
  return str;
}

/**
 * 查询是否为空对象
 * @param  {Object}  obj 查询对象
 * @return {Boolean}     查询结果
 */
export function isObjEmpty(obj) {
  // Speed up calls to hasOwnProperty
  const { hasOwnProperty } = Object.prototype;

  // null and undefined are "empty"
  if (obj == null) return true;

  // Assume if it has a length property with a non-zero value
  // that that property is correct.
  if (obj.length > 0) return false;
  if (obj.length === 0) return true;

  // If it isn't an object at this point
  // it is empty, but it can't be anything *but* empty
  // Is it empty?  Depends on your application.
  if (typeof obj !== 'object') return true;

  // Otherwise, does it have any properties of its own?
  // Note that this doesn't handle
  // toString and valueOf enumeration bugs in IE < 9
  let result = true;
  Object.keys(obj).forEach((key) => {
    if (hasOwnProperty.call(obj, key)) {
      result = false;
    }
  });

  return result;
}

/**
 * 获取标准分页数据
 * @param  {Object} data 源数据
 * @return {Object}      标准分页数据
 */
export function getPageData(data) {
  return {
    current: data.page,
    total: data.total,
    pageSize: data.pageSize,
    showSizeChanger: true,
    showTotal(total) {
      return `共有 ${total} 条记录`;
    },
    pageSizeOptions: data.pageSizeOptions ? data.pageSizeOptions : ['10', '50', '100'],
  };
}

/**
 * 通过枚举获取数组
 * @param  {Object} enumObj 枚举对象
 * @return {Array}          数组
 */
export function getEnumsArray(enumObj) {
  return Object.keys(enumObj).map(function (key) {
    return {
      text: enumObj[key],
      value: key,
    };
  });
}

/**
 * 过滤空数据
 */
export function filterEmptyData(data) {
  if (!data) return data;
  const filterData = data;
  Object.keys(filterData).forEach((inx) => {
    if (
      filterData[inx] === 'undefined' ||
      filterData[inx] === undefined ||
      filterData[inx] === null ||
      filterData[inx] === '' ||
      filterData[inx].length === 0
    )
      delete filterData[inx];
  });
  return filterData;
}

/**
 * 去除字符串空格
 */
export function trim(str, position) {
  const type = Object.prototype.toString.call(str).slice(8, -1);
  if (type !== 'String') return str;
  let result = '';
  switch (position) {
    case 'before': // 前
      result = str.replace(/(^\s*)/g, '');
      break;
    case 'after': // 后
      result = str.replace(/(\s*$)/g, '');
      break;
    case 'both': // 前后
      result = str.replace(/(^\s*)|(\s*$)/g, '');
      break;
    default:
      // 所有
      result = str.replace(/\s*/g, '');
  }
  return result;
}
